
var db=require("DB/dbConnect.js");
var client=db.connect();
var async = require('async');
var http = require("http");
var fs = require("fs");
var images = require("images");



exports.insertLog=function(logs,callback)
{
    db.insertLog(client,logs.start_time,logs.article_type_id,logs.level,logs.location,logs.message,logs.thread,logs.end_time,function(err,result){
          if(err) throw err;
          callback(err,result.affectedRows);
    });
}


exports.insertData=function(news,imgPath,callback)
{

    var title=news.title;
    var typeID=news.typeID;
    var date=news.date;
    var timespan="";
    var content=news.content.replace(/(\[\/?a.*?])|(\[\/?span.*?])/g,'').replace(/\s/g, "");
    var author=news.author;
    var source=news.source;
    var chanel=news.chanel;
	var dataUrl="";
    var picUrls=[];
	if(news.picUrls.length>0)
	{
       picUrls.push(news.picUrls[0]);
	}
    
    if(author)
    {
        if(author.indexOf("：")>0||author.indexOf(":")>0||author.indexOf("]")>0||author.indexOf("】")>0)
        {
            if(author.indexOf("：")>0)
            {
                //中文的冒号
                author=author.split("：");
            }
            else if(author.indexOf(":")>0)
            {
                author=author.split(":");

            }
            if(author[1].indexOf(")")>0||author[1].indexOf("]")>0)
            {
                author=author[1].substring(0,author[1].length-1);
            }
            else if(author[1].indexOf("】")>0)
            {
                author=author[1].substring(0,author[1].length-2);
            }
            else
            {
                author=author[1];
            }
        }
    }
    if(source)
    {
        if(source.indexOf(":")>0||source.indexOf("：")>0)
        {
            if(source.indexOf("：")>0)
            {
                //中文的冒号
                source=source.split("：")[1].trim();
            }
            else if(source.indexOf(":")>0)
            {
                source=source.split(":")[1].trim();
            }
        }
        else
        {
            source=source;
        }

    }
    //新闻日期
    if(date)
    {
        date=date.replace("年","-").replace("月","-").replace("月","-").replace("日"," ");
        timespan=new Date(date);
        timespan=timespan.getTime()/1000;
    }
    else
    {
        timespan=0;
    }

    if(news.title!="")
    {
        db.checkTitle(client,news.title,function(err,result){
            if(err) throw err;
            if(result.toString()=="0")
            {
                console.log("可以入库");
                downLoadPics(picUrls,function(dataUrl){
                    db.insertArticle(client,news.title,typeID,chanel,author,source,dataUrl,content,timespan,function(error,result){
                        if(error) throw error;
                        callback(error,result);
                        //console.log("插入文章成功");
                    })
                });
            }
            else
            {
                console.log("不可以入库");
            }
        })
    }
    else
    {
        console.log("标题不存在");
    }

    //下载图片
    function downLoadPics(picUrls,callback)
    {
        //下载图片，并存入数据库
        var imgNameArr=[];
        function getImages(pic,i,cb) {
			if(picUrls[i].indexOf("?")>0)
               {
                picUrls[i]=picUrls[i].substring(0,picUrls[i].indexOf("?"));
               }
            
            var imgUrl=picUrls[i].substring(picUrls[i].lastIndexOf("/")+1); //图片的保存名  xx.jpg
            var pathAll=imgPath+imgUrl; //download/20161009/xx.jpg
            imgNameArr.push(imgUrl);
            http.get(pic, function(resp){
                var imgData = "";
                resp.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
                resp.on("data", function(chunk){
                    imgData+=chunk;
                });
                resp.on("end", function(){
                    fs.writeFile(pathAll,imgData,"binary", function(err){
                        if(err){
                            console.log("图片地址错误！");
                            return cb(err);
                        }
                        console.log("图片地址正确！");
                        cb(null)
                    });
                });
            });
        }
        var i =0;
        async.mapLimit(picUrls, picUrls.length, function (pic, callback) {
            getImages(pic,i,function (err) {
                if(err){
                    callback(err);
                }else{
                    callback(null,1);
                }
            });
            i++;
        }, function (err, results) {
            if (err) {
                console.log(err);
            }
            if (results) {

                for(var i=0;i<imgNameArr.length;i++)
                {
					if(imgNameArr[i].indexOf("?")>0)
					{
                        imgNameArr[i]=imgNameArr[i].substring(0,imgNameArr[i].lastIndexOf("?"));
					}
					else
                    {
                        imgNameArr[i]=imgNameArr[i];
					}
                    if(imgNameArr[i].indexOf(".")<0||imgNameArr[i].split(".")[1].length>4)
                    {
                        //非图片格式
                        images(imgPath+imgNameArr[i])     //加载图像文件
                            .save(imgPath+imgNameArr[i].split(".")[0]+".jpg",{
                                quality : 50     //保存图片到文件,图片质量为50
                            });
                        fs.unlinkSync(imgPath+imgNameArr[i]);
                        imgNameArr[i]=imgNameArr[i].split(".")[0]+".jpg";
                        console.log("非图片格式下载成功!");
                    }
                    else
                    {
                        console.log("图片格式下载成功!");
                    }

                    //线上图片下载
                    imgNameArr[i]=imgPath.substring(18)+imgNameArr[i];

                    //本地图片下载
                    // imgNameArr[i]="/gather/"+imgPath.substring(3)+imgNameArr[i];
                    
                }
                dataUrl=imgNameArr[0];

                callback(dataUrl);
            }

        });
    }

}










